package com.finalministry.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataParam;

import com.finalministry.server.util.ResponseUtility;

@Path("/import")
public class ServiceImport extends IndexBase {

   @Path("/openimportfolder")
   public Response openImportFolder() {

      System.out.println(System.getProperty("os.name"));

      try {
         File here = new File("");
         Process p = new ProcessBuilder("explorer.exe", here.getAbsolutePath()).start();

         // File file = new File ("c:\<directory>");
         // Desktop desktop = Desktop.getDesktop();
         // desktop.open(file);
      } catch (Exception e) {
      };

      return Response.ok().build();
   }

	@POST
	@Path("/finalministry/{filename}")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	// @Produces(MediaType.TEXT_HTML)
	public Response import_finalministryXML(@FormDataParam("fmXmlFile") InputStream uploadedInputStream, @PathParam("filename") String filename)
			throws IOException {

		System.out.println("import_finalministryXML");

		if (uploadedInputStream == null) {

			return Response.status(200).entity(ResponseUtility.createErrorMessage("File input stream seems to be empty!")).build();
		}

		StringWriter writer = new StringWriter();
		IOUtils.copy(uploadedInputStream, writer, "UTF-8");
		String finalministryXML = writer.toString();
		return Response.status(200).entity(finalministryXML).build();
	}
}